<?php

/**
 * @author	barbarosalcin
 * @desc	ajax user
 * @version	$Id: 20110317
 * @package	ajax
 */

foreach ( $_POST as $key => $value )
{
	$_POST[$key] = str_replace("\n", '', $_POST[$key]);
	$_POST[$key] = str_replace("\r\n", '', $_POST[$key]);
	$_POST[$key] = preg_replace('%^<br />$%', '', $_POST[$key]);
	${$key} = strip_tags($_POST[$key]);
}

$postman_type = '';
switch ($req['get']['act'])
{
	case 'register' :
		
		if ($tk->session->data['session_logged_in'])
		{
			$error = 'logged_in';
			goto end;
		}
		
		foreach ( $_POST as $key => $value )
		{
			if ($key != 'user_password' && $key != 'user_password_2')
			{
				if ($value == '')
				{
					$error = 'data_required';
					goto end;
				}
			}
		}
		
		if ($user_password != $user_password_2)
		{
			$error = 'newpass_mismatch';
			goto end;
		}
		
		if (! $tk->f->validate_email($user_email))
		{
			$error = 'invalid_email';
			goto end;
		}
		
		$sql = "select user_id from " . USERS_TABLE . " where username = '{$username}' or user_email = '{$user_email}'";
		
		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		if ($tk->db->sql_numrows($result))
		{
			$error = 'user_exists';
			goto end;
		}
		
		$item_fields = 'username,user_firstname,user_surname,user_email,user_phone,user_title,user_association,user_actkey,user_password,user_active,user_level';
		$item_fields_additem = preg_replace('/(\w+)/i', '\'\$$1\'', $item_fields);
		$user_password_o = $user_password;
		$user_password = md5($user_password);
		$user_level = USER;
		
		// TODO: fix for activation required websites
		$user_active = 1;
		$user_actkey = '';
		
		eval("\$item_fields_additem = \"$item_fields_additem\";");
		
		$sql = "INSERT INTO " . USERS_TABLE . " ($item_fields,user_regdate) VALUES($item_fields_additem,'{$config['time']}')";
		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		$tk->postman->subject = $config['sitename'] . ' - ' . $lang['p_email']['remind'];
		$tk->postman->setfrom($config['contact_mail'], $config['contact_name']);
		$tk->postman->addaddress($user_email, $user_email);
		
		$tk->postman->assign_vars(array(
				'NAME' => $user_firstname . ' ' . $user_surname, 
				'USERNAME' => $username, 
				'SITENAME' => $config['sitename'], 
				'PASSWORD' => $user_password_o, 
				'IP' => $tk->f->decode_ip($user_ip), 
				'TIME' => date("H:i:s d.m.Y", $config['time'])));
		
		$postman_type = 'register';
	
	break;
	case 'remind' :
		
		if ($tk->session->data['session_logged_in'])
		{
			$error = 'logged_in';
			goto end;
		}
		
		if (! $tk->f->validate_email($user_email))
		{
			$error = 'invalid_email';
			goto end;
		}
		
		$sql = "select SQL_CACHE username,user_firstname,user_surname,username,user_active,user_level,user_actkey,user_newpasswd from " . USERS_TABLE . " where user_email = '$user_email' LIMIT 0,1";
		
		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		if (! ($tk->db->sql_numrows($result)))
		{
			$error = 'user_not_exist';
			goto end;
		}
		
		$row = $tk->db->sql_fetchrow($result);
		
		if ($row['user_active'] != 1)
		{
			$error = 'user_inactive';
			goto end;
		}
		
		if ($row['user_level'] != USER)
		{
			$error = 'protected_account';
			goto end;
		}
		
		if ($row['user_actkey'] != '' && $row['user_newpasswd'] != '')
		{
			$error = 'newpass_process';
			goto end;
		}
		
		$newpasswd = $tk->f->generatePassword(8);
		$user_actkey = md5($config['time']);
		
		$sql = "update " . USERS_TABLE . " set user_actkey='$user_actkey',user_newpasswd='" . md5($newpasswd) . "' where user_email = '$user_email'";
		
		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		$tk->postman->subject = $config['sitename'] . ' - ' . $lang['p_email']['register'];
		$tk->postman->setfrom($config['contact_mail'], $config['contact_name']);
		$tk->postman->addaddress($user_email, $user_email);
		
		$tk->postman->assign_vars(array(
				'NAME' => $row['user_firstname'] . ' ' . $row['user_surname'], 
				'SITENAME' => $config['sitename'], 
				'USERNAME' => $newpasswd,
				'PASSWORD' => $newpasswd, 
				'U_ACTIVATE' => $config['siteurl'] . $config['docroot'] . 'login/remindact/' . $config['default_index'] . '?email=' . $user_email . '&actkey=' . $user_actkey, 
				'IP' => $tk->f->decode_ip($user_ip), 
				'TIME' => date("H:i:s d.m.Y", $config['time'])));
		
		$postman_type = 'remind';
	
	break;
	
	case 'userinfo_save' :
		
		if (! $tk->session->data['session_logged_in'])
		{
			$error = 'not_logged_in';
			goto end;
		}
		
		foreach ( $_POST as $key => $value )
		{
			if ($key != 'user_password' && $key != 'user_password_2')
			{
				if ($value == '')
				{
					$error = 'data_required';
					goto end;
				}
			}
		}
		
		if (md5($current_password) != $tk->session->data['user_password'])
		{
			$error = 'current_password';
			goto end;
		}
		
		if (!$tk->f->validate_email($user_email))
		{
			$error = 'invalid_email';
			goto end;
		}
		
		if ($user_password != $user_password_2)
		{
			$error = 'newpass_mismatch';
			goto end;
		}
		
		$item_fields = 'user_firstname,user_surname,user_email,user_phone,user_title,user_association';
		$item_fields_manitem = preg_replace('/(\w+)/i', '$1=\'\$$1\'', $item_fields);
		eval("\$item_fields_manitem = \"$item_fields_manitem\";");
		
		$newpass_email = 0;
		
		if ($user_password != '')
		{
			$item_fields_manitem .= ",user_password='" . md5($user_password) . "',user_actkey='" . md5($config['time']) . "'";
			$newpass_email = 1;
		}
		
		$sql = "UPDATE " . USERS_TABLE . " set $item_fields_manitem where user_id ='{$tk->session->data['user_id']}'";
		
		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}

	
	break;
	
	case 'writemail' :
		if (! $tk->session->data['session_logged_in'])
		{
			$error = 'not_logged_in';
			goto end;
		}
		
		foreach ( $_POST as $key => $value )
		{
			if ($value == '')
			{
				$error = 'required_field';
				goto end;
			}
		}
		
		$tk->postman->subject = $config['sitename'] . ' - ' . $subject;
		$tk->postman->setfrom($tk->session->data['user_email'], $tk->session->data['user_firstname'] . ' ' . $tk->session->data['user_surname']);
		$tk->postman->addaddress($config['contact_mail'], $config['contact_name']);
		
		$tk->postman->assign_vars(array(
				'NAME' => $tk->session->data['user_firstname'] . ' ' . $tk->session->data['user_surname'] . '(' . $tk->session->data['username'] . ')', 
				'MESSAGE' => $message, 
				'IP' => $tk->f->decode_ip($user_ip), 
				'TIME' => date("H:i:s d.m.Y", $config['time'])));
		
		$postman_type = 'contact';
		

		goto sendmail;
	
	break;
	case 'login' :

		$username = preg_replace('%[^A-Za-z0-9_-]%i','', $username);
		
		if ($username == '' || $password == '')
		{
			$error = 'data_required';
			goto end;
		}
		
		$sql = "SELECT SQL_CACHE user_id,username,user_password,user_plain_password,user_active,user_level,user_login_tries,user_last_login_try
					 from " . USERS_TABLE . " 
					 WHERE username = '$username'";

		if (! ($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		if (! $tk->db->sql_numrows($result))
		{
			$error = 'user_not_exist';
			goto end;
		}
		
		$row = $tk->db->sql_fetchrow($result);

		if ((md5($password) == $row['user_password']) && $row['user_active'] == 1)
		{
			
			$admin = (isset($HTTP_POST_VARS['admin'])) ? 1 : 0;
			$autologin = (isset($HTTP_POST_VARS['autologin'])) ? TRUE : 0;
			
			$tk->session->begin($row['user_id'], $user_ip, $pagename, FALSE, $autologin, $admin);
			
			$sql = "insert into " . USERS_LOG_TABLE . " (user_id,time,ip) VALUES('{$tk->session->data['user_id']}','{$tk->session->data['session_start']}','{$tk->session->data['session_ip']}')";
			
			if (! ($result = $tk->db->sql_query($sql)))
			{
				$error = 'sql';
				goto end;
			}
		}
		else
		{
			$error = 'wrong_pass_or_user_inactive';
			goto end;
		}

	
	break;
	case 'remindact':

		if(!preg_match('%^[A-Za-z0-9]{32}$%i',$_POST['actkey']))
		{
			$error = 'invalid_actkey';
			goto end;
		}
		
		if (!$tk->f->validate_email($_POST['email']))
		{
			$error = 'invalid_email';
			goto end;
		}		
		
		$sql = "select SQL_CACHE user_newpasswd from ".USERS_TABLE." where user_actkey = '{$_POST['actkey']}' and user_level = '".USER."' and user_email='{$_POST['email']}'";
		
		if(!($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}
		
		
		$row = $tk->db->sql_fetchrow($result);
		
		if (! $tk->db->sql_numrows($result) || $row['user_newpasswd'] == '')
		{
			$error = 'reminder_not_exist';
			goto end;
		}
		
		$sql = "update ".USERS_TABLE." set user_password='{$row['user_newpasswd']}',user_newpasswd = '',user_actkey='' where user_email='{$_POST['email']}' and user_actkey='{$_POST['actkey']}'";
		
		if(!($result = $tk->db->sql_query($sql)))
		{
			$error = 'sql';
			goto end;
		}

		
		break;
	default :
		$error = 'undefined';
		goto end;
	break;
}


$data_json['header'] = $lang['json'][$type][$req['get']['act']]['header'];
$data_json['message'] = $lang['json'][$type][$req['get']['act']]['message'];

sendmail:

if ($postman_type != '')
{
	$tk->postman->ishtml(true);
	
	if (! $tk->postman->sendmail($postman_type))
	{
		
		$error = 'sendmail';
		goto end;
	}
}
end: